package com.cf.snake;

import java.util.List;
import java.util.concurrent.TimeUnit;

import com.cf.snake.modele.Direction;
import com.cf.snake.modele.ModeleDuJeu;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements SurfaceHolder.Callback  {
	private static int SurfaceWidth = 0;
	private static int SurfaceHeight = 0;
	private static final int SCORE_PER_BLOCK = 10;
	private int sBlockWidth;
	private int sBlockHeight;

	private Bitmap mSnakeBody;
	private Bitmap mSnakeHead;
	private Paint backgroundPaint;
	float ballX = 0, ballY = 0;

	TextView txtScore;
	private int mScore = 0;
	private Handler mHandler;
	Button btnThread;
	
	

	
	private ModeleDuJeu modele;
	private SurfaceView surface;
	private SurfaceHolder holder;
	private Object mPauseLock;
	private boolean mPaused;
	private ThreadSnake thread;
	Button butLeft, butRight, butUp, butDown;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		//Variables du jeu
		modele = new ModeleDuJeu();
		mPauseLock = new Object();
		mPaused = false;
		//Boutons
		butLeft = (Button)this.findViewById(R.id.bLeft);
		butRight = (Button)this.findViewById(R.id.bRight);
		butUp = (Button)this.findViewById(R.id.bUp);
		butDown = (Button)this.findViewById(R.id.bDown);
		butLeft.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				modele.gestionDirection(Direction.VERS_LA_GAUCHE);				
			}
		});
		butRight.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				modele.gestionDirection(Direction.VERS_LA_DROITE);				
			}
		});
		butUp.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				modele.gestionDirection(Direction.VERS_LE_HAUT);				
			}
		});
		butDown.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				modele.gestionDirection(Direction.VERS_LE_BAS);				
			}
		});
		
		//Surfaces pour dessiner
		surface = (SurfaceView)this.findViewById(R.id.surface);
		holder = surface.getHolder();
		surface.getHolder().addCallback(this);
		//Thread du jeu
		thread = new ThreadSnake();
		thread.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onPause() {
		super.onPause();

		synchronized (mPauseLock) {
			mPaused = true;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		synchronized (mPauseLock) {
			mPaused = false;
			mPauseLock.notifyAll();
		}
	}
	// Methode dessin
		private void draw() {

			Canvas c = null;
			try {
				c = holder.lockCanvas();
				
				//c.drawARGB(50, 255, 0, 0);
				if (c != null) {
					doDraw(c);
				}
			} finally {
				if (c != null) {
					holder.unlockCanvasAndPost(c);
				}
			}
		}

		// dessiner dans canvas sil nest pas null
		private void doDraw(Canvas c) {
			int width = c.getWidth();
			int height = c.getHeight();
			//Dessiner background
			Paint blanc = new Paint();
			blanc.setColor(Color.BLUE);
			c.drawRect(0, 0, width, height, blanc );
			//Dessin du modele avec serpent et grenouille.
			modele.affichage(c);
			/*
			sBlocks = sModel.getSnakeBlocks();
			int size = sBlocks.size();

			mScore = (size - 3) * SCORE_PER_BLOCK;
			// Exception will be thrown if you try to do setText here
			// Only the main thread that created TextView can do setText.
			// So, we need to use handlers for the same
			mHandler.sendEmptyMessage(size);

			// Draw Snake Head with Different bitmap
			c.drawBitmap(mSnakeHead, sBlocks.get(0).x_loc, sBlocks.get(0).y_loc,
					null);

			// Draw rest of the Snake Body
			for (int index = 1; index < size; index++) {
				c.drawBitmap(mSnakeBody, sBlocks.get(index).x_loc,
						sBlocks.get(index).y_loc, null);
			}
			// Draw the block to be eaten up..
			eatBlock = sModel.getEatBlock();
			c.drawBitmap(mSnakeBody, eatBlock.x_loc, eatBlock.y_loc, null);
			*/
		}

		// Create a private class for GameLoop
		// This will call draw() method of the main class at regular interval
		private class ThreadSnake extends Thread {
			private volatile boolean running = true;

			public void run() {
				while (running) {
					try {
						/*if (!holder.getSurface().isValid()){
							continue;
						}*/
						// Here is one Hard coding..
						TimeUnit.MILLISECONDS.sleep(15);
						
						modele.calcul();
						draw();
						running = !modele.isLaPartieEstPerdue();

					} catch (InterruptedException ie) {
						running = false;
					}
					synchronized (mPauseLock) {
						while (mPaused) {
							try {
								mPauseLock.wait();
							} catch (InterruptedException e) {
							}
						}
					}
				}
			}

			public void safeStop() {
				running = false;
				interrupt();
			}
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			// Get the width and height of SurfaceView
			//getSurfaceDimension();

			// Pass the width/height into Model
			//sModel.init(SurfaceWidth, SurfaceHeight, sBlockWidth);
			// Start game loop
			thread = new ThreadSnake();
			thread.start();
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			try {
				thread.safeStop();
			} finally {
				thread = null;
			}
		}
}
